package com.nus;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.nus.parsers.ParserAPIs;
import com.nus.representations.IvleModule;
import com.nus.representations.IvleWorkbin;

public class IvleWorkbinActivity extends Activity {
	private ListView lv;

	private ArrayList<IvleWorkbin> workbin;
	private long PROGRESS;
	File dir;
	protected TextView title;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	
		setContentView(R.layout.ivleworkbinlayout);
//		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
//		 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
//		 title = (TextView) findViewById(R.id.title);
//		 title.setText("Workbin");
		String url = "https://ivle.nus.edu.sg/api/Lapi.svc/Workbins?APIKey=W7RtgW7GZKUpaEkJ1NwUD&AuthToken="
				+ NUS_Android.IVLE_Token
				+ "&CourseID="
				+ IvleModuleActivity.COURSE_ID
				+ "&Duration=0&WorkbinID=&TitleOnly=false&output=json";
		try {
			String response = getResponseText(url);

			Log.i("Response", response);

			workbin = ParserAPIs.parseIvleWorkbin(response);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		lv = (ListView) findViewById(R.id.list_view);

		lv.setAdapter(new ListAdapter(IvleWorkbinActivity.this,
				R.id.workbin_item, workbin));

	}

	public String getResponseText(String stringUrl) throws IOException {
		StringBuilder response = new StringBuilder();

		URL url = new URL(stringUrl);
		HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
		if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			BufferedReader input = new BufferedReader(new InputStreamReader(
					httpconn.getInputStream()), 8192);
			String strLine = null;
			while ((strLine = input.readLine()) != null) {
				response.append(strLine);
			}
			input.close();
		}
		return response.toString();
	}

	private class ListAdapter extends ArrayAdapter<IvleWorkbin> { // --
		// CloneChangeRequired
		private ArrayList<IvleWorkbin> mList; // --CloneChangeRequired
		private Context mContext;
		private EditText input;

		public ListAdapter(Context context, int textViewResourceId,
				ArrayList<IvleWorkbin> list) { // --CloneChangeRequired
			super(context, textViewResourceId, list);
			this.mList = list;
			this.mContext = context;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			try {
				if (view == null) {
					LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = vi.inflate(R.layout.ivleworkbinlayoutitem, null);
				}
				final IvleWorkbin listItem = mList.get(position);
				if (listItem != null) {
					// setting list_item views
					TextView tv = (TextView) view
							.findViewById(R.id.folder_name);
					tv.setText(listItem.getFolderName());
					TextView tv2 = (TextView) view.findViewById(R.id.file_name);
					//tv2.setTextColor(Color.BLUE);
					tv2.setClickable(true);
					
					tv2.setClickable(true);
					Log.i("modules",
							"workbin file name" + listItem.getFileName());
					tv2.setText(listItem.getFileName());
					tv2.setHighlightColor(Color.BLUE);
					TextView tv3 = (TextView) view
							.findViewById(R.id.close_date);
					//tv3.setTextColor(Color.BLUE);
					tv3.setText(listItem.getFolderCloseDate());
					tv2.setOnClickListener(new OnClickListener() {
						public void onClick(View arg0) {
							String url = "https://ivle.nus.edu.sg/api/downloadfile.ashx?APIKey=W7RtgW7GZKUpaEkJ1NwUD&AuthToken="
									+ NUS_Android.IVLE_Token
									+ "&ID="
									+ listItem.getFileID() + "&target=workbin";
							// // Intent downloadIntent = new
							// Intent(Intent.ACTION_VIEW, Uri.parse(url));
							final String MIME_TYPE_PDF = "application/pdf";
							Intent browserIntent = new Intent(
									Intent.ACTION_VIEW);
							browserIntent.setType(MIME_TYPE_PDF);
							browserIntent.setData(Uri.parse(url));
							startActivity(browserIntent);
							Log.i(" workbin", " url is" + url);

							// URL u;
							// try {
							// u = new URL(url);
							// // new DownloadFilesTask().execute();
							// File sdCard =
							// Environment.getExternalStorageDirectory();
							// dir= new File (sdCard.getAbsolutePath() +
							// "/download");
							// dir.mkdirs();
							// File file = new File(dir,
							// listItem.getFileName());
							//
							// FileOutputStream f = new FileOutputStream(file);
							//
							// // String root =
							// Environment.getExternalStorageDirectory()+"/download/"+listItem.getFileName();
							//
							// HttpURLConnection c = (HttpURLConnection)
							// u.openConnection();
							// c.setRequestMethod("GET");
							// c.setDoOutput(true);
							// c.connect();
							//
							// int lenghtOfFile = c.getContentLength();
							//
							// // FileOutputStream f = new FileOutputStream(new
							// File(root));
							//
							// InputStream in = c.getInputStream();
							//
							// byte[] buffer = new byte[1024];
							// int len1 = 0;
							// long total = 0;
							//
							// while ((len1 = in.read(buffer)) > 0) {
							// total += len1; //total = total + len1
							// PROGRESS=(total*100)/lenghtOfFile;
							// // setSecondaryProgress("" +
							// (int)((total*100)/lenghtOfFile));
							// f.write(buffer, 0, len1);
							// }
							// f.close();
							//
							// }
							// catch (MalformedURLException e) {
							// // TODO Auto-generated catch block
							// e.printStackTrace();
							// }
							// catch(Exception e){
							// e.printStackTrace();
							// }
							//
							// File file = new
							// File(dir+"/"+listItem.getFileName());
							//
							// PackageManager packageManager =
							// getPackageManager();
							// Intent testIntent = new
							// Intent(Intent.ACTION_VIEW);
							// testIntent.setType("application/pdf");
							// List list =
							// packageManager.queryIntentActivities(testIntent,
							// PackageManager.MATCH_DEFAULT_ONLY);
							// if (list.size() > 0 && file.isFile()) {
							// Intent intent = new Intent();
							// intent.setAction(Intent.ACTION_VIEW);
							// Uri uri = Uri.fromFile(file);
							// intent.setDataAndType(uri, "application/pdf");
							//
							// startActivity(intent);
							// }
							
						}
					});
                       
				}
			} catch (Exception e) {
				Log.i(IvleWorkbinActivity.ListAdapter.class.toString(),
						e.getMessage());
			}
			return view;
		}
	}

	private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
		private ProgressDialog Dialog = new ProgressDialog(
				IvleWorkbinActivity.this);

		protected void onPreExecute() {
			Dialog.setMessage("Starting pre-execute...");
			Dialog.show();
		}

		protected Void doInBackground(Void... v) {
			Dialog.setMessage(" saving doInbackground data");
			return null;
			// int count = urls.length;
			// long totalSize = 0;
			// for (int i = 0; i < count; i++) {
			// // totalSize += Downloader.downloadFile(urls[i]);
			// publishProgress((int) ((i / (float) count) * 100));
			// }
			// return totalSize;
		}

		protected void onProgressUpdate(Integer... progress) {
			Dialog.setMessage(" saving onProgressUpdate data");
		}

		protected void onPostExecute(Long result) {
			Dialog.dismiss();

			Toast.makeText(IvleWorkbinActivity.this,
					"Source: " + dir.getAbsolutePath(), Toast.LENGTH_LONG)
					.show();

		}

		// @Override
		// protected Void doInBackground(String... arg0) {
		// // TODO Auto-generated method stub
		// Dialog.setMessage(" saving data"+PROGRESS);
		// return null;
		// }
	}

}
